package com.base.common.util.log;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import com.base.common.common.Constant;
import com.base.common.util.date.DateUtil;
import com.yf.cmw.constant.BussConstant;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class CrashHandler implements Thread.UncaughtExceptionHandler{
    private static final String TAG = "CrashHandler";
	//系统默认的UncaughtException处理类
	private Thread.UncaughtExceptionHandler mDefaultHandler;
	//CrashHandler实例
	private static CrashHandler INSTANCE;

	private Context mContext;

	//用来存储设备信息和异常信息
	private Map<String, String> infos = new HashMap<String, String>();

	public static CrashHandler getInstace() {
		return INSTANCE;
	}

	public CrashHandler(Context context) {
		mContext = context;
		//获取系统默认的UncaughtException处理器
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		//设置该CrashHandler为程序的默认处理器
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	public static void init(Context context) {
		if (INSTANCE == null) {
			INSTANCE = new CrashHandler(context);
		}
	}


	@Override
	public void uncaughtException(Thread thread, Throwable ex) {

		if (!handleException(ex) && mDefaultHandler != null) {
			//如果用户没有处理则让系统默认的异常处理器来处理
			mDefaultHandler.uncaughtException(thread, ex);
		} else {
//			try {
//				Thread.sleep(3000);
//			} catch (InterruptedException e) {
//
//			}
//			//退出程序
//			android.os.Process.killProcess(android.os.Process.myPid());
//			System.exit(0);
//
//			ToastAlert.showMsg("应用重启");
//			restartApplication();
		}
		restartApp();
	}


    private void restartApp() {
        Log.e(TAG,"应应崩溃，调用 restartApp 方法延时1秒后重启APP，并关闭当前应用！");
//        Intent intent = new Intent(this, MainActivity.class);
        final Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(mContext.getPackageName());
        @SuppressLint("WrongConstant") PendingIntent restartIntent = PendingIntent.getActivity(
                mContext.getApplicationContext(), 0, intent,Intent.FLAG_ACTIVITY_NEW_TASK);
        //退出程序
        AlarmManager mgr = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 3000,
                restartIntent); // 3秒钟后重启应用

        //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }


	private void restartApplication() {
		final Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(mContext.getPackageName());
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		mContext.startActivity(intent);
	}

	/**
	 * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
	 *
	 * @param ex
	 * @return true:如果处理了该异常信息;否则返回false.
	 */
	private boolean handleException(Throwable ex) {
		if (ex == null) {
			return false;
		}
		//使用Toast来显示异常信息
//		new Thread() {
//			@Override
//			public void run() {
//				Looper.prepare();
//				ToastAlert.showMsg("很抱歉,程序出现异常,即将退出");
//				Looper.loop();
//			}
//		}.start();

		//收集设备参数信息
		collectDeviceInfo(mContext);
		//保存日志文件
		handleThrowable(ex);
		return true;
	}

	/**
	 * 收集设备参数信息
	 * @param ctx
	 */
	public void collectDeviceInfo(Context ctx) {
		try {
			PackageManager pm = ctx.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
			if (pi != null) {
				String versionName = pi.versionName == null ? "null" : pi.versionName;
				String versionCode = pi.versionCode + "";
				infos.put("versionName", versionName);
				infos.put("versionCode", versionCode);
			}
		} catch (PackageManager.NameNotFoundException e) {

		}

		Field[] fields = Build.class.getDeclaredFields();
		for (Field field : fields) {
			try {
				field.setAccessible(true);
				infos.put(field.getName(), field.get(null).toString());
			} catch (Exception e) {

			}
		}
	}


	public void handleThrowable(Throwable ex) {

		StringBuffer sb = new StringBuffer();
		sb.append(Constant.LOG_TIME+ DateUtil.getCurrentDateTime() + "\n");
		for (Map.Entry<String, String> entry : infos.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			sb.append(key + "=" + value + "\n");
		}

		Writer writer = new StringWriter();
		PrintWriter pw = new PrintWriter(writer);
		ex.printStackTrace(pw);
		Throwable cause = ex.getCause();
		while (cause != null) {
			cause.printStackTrace(pw);
			cause = cause.getCause();
		}

		pw.close();

		sb.append(writer.toString());

		saveTologFile(sb.toString());
	}

	/**
	 * 获取广告资源存放目录
	 * @return
	 */
	private String getAdLogPath(){
		String logDir = BussConstant.LOG_ADPATH;
		File file = new File(logDir);
		if(!file.exists()){
			boolean flag = file.mkdirs();
			Log.i(TAG,String.format("日志文件目录：%s 创建 %s！", logDir, (flag ? "成功" : "失败")));
		}
		return logDir;
	}

	private void saveTologFile(String log) {
		FileWriter fw = null;
		PrintWriter pw = null;
		try {
			String logDir = getAdLogPath();
			File logFile = new File(logDir, Constant.LOG_PROJECT+ DateUtil.getCurrentDate()+".txt");
			if (!logFile.exists()) {
				logFile.createNewFile();
			}
			fw = new FileWriter(logFile, true);
			pw = new PrintWriter(fw);
			pw.print(log + "\r\n");
			pw.flush();
			fw.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e) {

				}
			}

			if (pw != null) {
				pw.close();
			}
		}
	}

}